package com.ptswitch.material.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hxzon.util.BitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ptswitch.material.dao.PermissionMapper;
import com.ptswitch.material.model.security.Permission;
import com.ptswitch.material.service.PermissionService;
import com.ptswitch.material.util.security.PermissionUtil;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void initPermissions() {
        List<Permission> dbPermissions = findAll(Init_Roles);
        Map<String, Permission> dbPermissionMap = new HashMap<String, Permission>();
        for (Permission p : dbPermissions) {
            dbPermissionMap.put(p.getPermissionName(), p);
        }
        List<Permission> newPermissions = new ArrayList<Permission>();
        for (Permission p : PermissionUtil.permissions) {
            Permission dbP = dbPermissionMap.get(p.getPermissionName());
            if (dbP == null) {
                newPermissions.add(p);
            } else {
                p.setId(dbP.getId());
            }
        }
        for (Permission p : newPermissions) {
            save(p);
        }
    }

    @Override
    public Permission findById(long id, int init) {
        if (BitUtil.isSet(init, Init_Roles)) {
            return permissionMapper.findByIdWithRoles(id);
        }
        Permission result = permissionMapper.findById(id);
        return result;
    }

    @Override
    public List<Permission> findAll(int init) {
//        String hql = " from Permission p ";
//        if (BitUtil.isSet(init, Init_Roles)) {
//            hql += " join fetch p.roles ";
//        }
        return permissionMapper.findAll(init, -1, -1);
    }

    @Override
    public List<Permission> findAll() {
        return findAll(Init_None);
    }

    @Override
    public void save(Permission permission) {
        long id = permissionMapper.add(permission);
        permission.setId(id);
    }

}
